package com.th.therp.service.Impl;

import com.th.therp.exception.BaseException;
import com.th.therp.mapper.StoreMapper;
import com.th.therp.pojo.emtity.Store;
import com.th.therp.service.InventoryService;
import com.th.therp.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    @Lazy
    private InventoryService inventoryService;

    @Override
    public List<Store> list() {
        return storeMapper.list();
    }

    @Override
    public void add(Store store) {
        Store existingStore = storeMapper.findByName(store.getName());
        if (existingStore == null) {
            storeMapper.add(store);
        }else {
            throw new BaseException("该仓库已存在");
        }
    }

    @Override
    public void update(Store store) {
        Store existingStore = storeMapper.findByName(store.getName());
        if (existingStore != null && !existingStore.getId().equals(store.getId())) {
            throw new BaseException("该仓库已存在");
        }else {
            storeMapper.update(store);
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        ids.forEach(id -> {
            Integer quantity = inventoryService.findQuantityByStoreId(id);
            String storeName = storeMapper.findNameById(id);
            if (quantity > 0) {
                throw new BaseException(storeName+"：该仓库有商品，不可删除");
            }else {
                Store store = Store.builder()
                        .id(id)
                        .isDeleted(1)
                        .build();
                storeMapper.update(store);
            }
        });
    }

    @Override
    public String findNameById(Integer storeId) {
        return storeMapper.findNameById(storeId);
    }
}